import {View, StyleSheet, TextInput, Text, Image, ScrollView, Alert, Platform, PermissionsAndroid} from 'react-native';
import React, {Component} from 'react';
import {Flex, Radio, List, InputItem, WhiteSpace, Modal, PickerView, Provider, Button, Toast} from '@ant-design/react-native';
import {connect} from 'react-redux';
import {saveComHouseInfo} from '~/api/owner';
import {getBuildListByCityId} from '~/api/company';
import Albums from '~/pages/home/album/Album';
import {getBankLoanByBankId} from '~/api/bank';
import {init, setLocatingWithReGeocode, Geolocation} from 'react-native-amap-geolocation';
import {getGeoCity, getCityListOfOpen, getPopularCityListOfOpen} from '~/api/public';
import {saveSystem} from '~/store/system';
import {saveParkOrder} from '~/store/parkorder';
import {getParkingPlanItemInfo} from '~/api/parking';

const RadioItem = Radio.RadioItem;

const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
        system: state.system,
        parkorder: state.parkorder,
    };
};

const mapSetter = (dispatch) => {
    return {
        onparkSave: (data) => {
            dispatch(saveParkOrder(data));
        },
    };
};
class Information extends Component {
    static navigationOptions = {
        title: '补全业主信息',
    };

    constructor(props) {
        super(props);
        this.state = {
            parkinginfo: this.props.navigation.getParam('parkinginfo'),
            parkingplanitem: [],
            IDCard: '',
            HouseOwner: '',
            HouseNo: '',
            checked: false,
            CityID: this.props.system.city_id,
            CityName: this.props.system.city,
            visible: false,
            buildlist: [],
            buildId: 0,
            buildName: '',
            OwnerFileID: [],
        };
        this.getbuildcitylist();
        getParkingPlanItemInfo(this.state.parkinginfo.ParkingPlanItemID).then((r) => {
            if (r.code === 0) {
                this.setState({
                    parkingplanitem: r.data,
                });
            }
        });
        this.onpresss = () => {
            this.setState({
                checked: !this.state.checked,
            });
        };
        this.onChange = (value) => {
            let item = this.state.buildlist.find((item) => item.value === value[0]);
            this.setState({
                buildName: item.label,
                buildId: value[0],
            });
        };
        this.onClose = () => {
            this.setState({
                visible: false,
            });
        };
        //热门城市
        getPopularCityListOfOpen().then((r) => {
            if (r.code === 0) {
            } else {
                alert('获取热门的开放城市失败：' + r.msg);
            }
        });
        getCityListOfOpen().then((r) => {
            if (r.code === 0) {
                let city_list = [];
                let temp_list = [];
                let letter = '';
                r.data.forEach((item) => {
                    if (item.FirstLetter != letter) {
                        if (letter != '') {
                            city_list.push({
                                letter: letter,
                                list: temp_list,
                            });
                        }
                        letter = item.FirstLetter;
                        temp_list = [];
                    }
                    temp_list.push(item);
                });
                city_list.push({
                    letter: letter,
                    list: temp_list,
                });
            } else {
                alert('获取开放城市列表失败：' + r.msg);
            }
        });
    }

    async initPostion() {
        // android需要手动获取定位权限
        if (Platform.OS === 'android') {
            await PermissionsAndroid.requestMultiple([
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
            ]);
        }

        // 初始化高德地图SDK
        await init({
            ios: '05e2900e6e7230c91a628709b777b333',
            android: '55322c82dac3b82cb8ddf649e55f5288',
        });

        // 设定iOS获取定位包含逆地理编码
        if (Platform.OS === 'ios') {
            setLocatingWithReGeocode(true);
        }

        this.getLocation();
    }

    getLocation() {
        if (this.props.system.city === '') {
            Geolocation.getCurrentPosition(
                ({location}) => {
                    getGeoCity({city_id: location.adCode}).then((r) => {
                        if (r.code === 0) {
                            let city = location.district || location.city;
                            let city_id = location.adCode;
                            this.setState({
                                CityName: city,
                                CityID: city_id,
                            });
                        } else {
                            Modal.alert('提示', '你所在城市未开放，请手动选择其它开放的城市。', [
                                {
                                    text: '确定',
                                    onPress: () => {
                                        this.onGoCityPage();
                                    },
                                },
                            ]);
                        }
                    });
                },
                (error) => {
                    alert('获取定位失败：' + error.message);
                },
            );
        } else {
            this.setState({
                CityName: this.props.system.city,
                CityID: this.props.system.city_id,
            });
        }
    }

    onGoCityPage = () => {
        this.props.navigation.navigate('City', {
            updateCityName: (CityName, CityID) => {
                this.setState(
                    {
                        CityName,
                        CityID,
                    },
                    () => {
                        this.getbuildcitylist();
                    },
                );
            },
        });
    };
    getbuildcitylist = () => {
        getBuildListByCityId(this.state.CityID).then((r) => {
            if (r.code === 0) {
                let list = [];
                r.data.forEach((item) => {
                    list.push({
                        label: item.BuildingName,
                        value: item.CompanyBuildingID,
                    });
                });
                list.push({
                    label: '其他',
                    value: 111,
                });
                this.setState(
                    {
                        buildlist: list,
                    },
                    () => {
                        let item = this.state.buildlist.find((item) => item.value === this.state.parkinginfo.CompanyBuildingID);
                        if (item != '') {
                            this.setState({
                                buildName: item.label,
                                buildId: this.state.parkinginfo.CompanyBuildingID,
                            });
                        }
                    },
                );
            } else {
                Alert.alert('111失败');
            }
        });
    };
    setbuildName = (text) => {
        this.setState({
            buildName: text,
        });
    };
    render() {
        var idcard_regx = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
        const onPress = () => {
            if (this.state.HouseOwner === '') {
                Toast.info('请输入姓名', 1);
            } else if (this.state.IDCard === '') {
                Toast.info('请输入身份证号', 1);
            } else if (this.state.HouseNo === '') {
                Toast.info('请输入门牌号', 1);
            } else if (this.state.buildId === 0) {
                Toast.info('请选择小区', 1);
            } else if (!idcard_regx.test(this.state.IDCard)) {
                Toast.info('请输入正确得身份证号码', 1);
            } else {
                saveComHouseInfo({
                    IDCard: this.state.IDCard,
                    OwnerHouseID: 0,
                    CompanyBuildingID: this.state.buildId,
                    HouseOwner: this.state.HouseOwner,
                    HouseNo: this.state.HouseNo,
                    OwnerFileID: this.state.OwnerFileID,
                    BuildingName: this.state.buildName,
                }).then((r) => {
                    if (r.code === 0) {
                        if (this.state.buildName != '其他') {
                            this.props.onparkSave({
                                parkingid: this.state.parkinginfo.ParkingDataID,
                                ownerhouseid: r.data.OwnerHouseID,
                                projectid: this.state.parkinginfo.ProjectDataID,
                                companybuildingid: this.state.parkinginfo.CompanyBuildingID,
                                parkinginfo: this.state.parkinginfo,
                                parkingplanid: this.state.parkingplanitem.ParkingPlanID,
                                parkingplanitemid: this.state.parkingplanitem.ParkingPlanItemID,
                                parkingplanitem: this.state.parkingplanitem,
                            });
                        }
                        this.props.navigation.replace('Process');
                    } else {
                        Toast.info(r.msg, 1);
                    }
                });
            }
        };
        const setNumber = (text) => {
            this.setState({
                IDCard: text,
            });
        };
        const setName = (text) => {
            this.setState({
                HouseOwner: text,
            });
        };
        const setMen = (number) => {
            this.setState({
                HouseNo: number,
            });
        };
        return (
            <>
                <ScrollView style={styles.srcollview}>
                    <View
                        style={{
                            width: '100%',
                            height: 60,
                            backgroundColor: '#F8F8FC',
                            justifyContent: 'center',
                            flexDirection: 'column',
                            paddingLeft: 16,
                        }}>
                        <Text style={{fontSize: 14, color: '#A3A3A3'}}>个人基础信息</Text>
                    </View>
                    <WhiteSpace size={'xs'} />
                    <View style={styles.userviews}>
                        <Text style={styles.userText}>真实姓名</Text>
                        <View style={styles.nameinputstyle}>
                            <List>
                                <InputItem placeholder="请输入姓名" onChange={setName} />
                            </List>
                        </View>
                    </View>
                    <WhiteSpace size={'xs'} />
                    <View style={styles.view}>
                        <View
                            style={{
                                flexDirection: 'column',
                                justifyContent: 'center',
                                flex: 1,
                            }}>
                            <View style={styles.userviews}>
                                <Text style={styles.userText}>身份证号码</Text>
                                <View style={styles.nameinputstyle}>
                                    <List>
                                        <InputItem type={'number'} maxLength={18} placeholder="请输入身份证号码" onChange={setNumber} />
                                    </List>
                                </View>
                            </View>
                            <WhiteSpace size="xs" />
                            <Flex
                                justify={'between'}
                                style={{
                                    width: '100%',
                                    padding: 15,
                                }}>
                                <Text
                                    // onPress={this.onGoCityPage}
                                    style={{
                                        fontSize: 14,
                                        color: '#333333',
                                    }}>
                                    当前城市为：{this.state.CityName}
                                    <Image
                                        style={{
                                            width: 10,
                                            height: 11,
                                        }}
                                        source={require('~/assets/shouye/dizhi_12x.png')}
                                    />
                                </Text>

                                <Text
                                    style={{}}
                                    onPress={() => {
                                        this.state.parkinginfo.CompanyBuildingID === 0 && this.setState({visible: true});
                                        if (this.state.buildId === 0 && this.state.buildlist.length > 0) {
                                            this.setState({
                                                buildId: this.state.buildlist[0].value,
                                                buildName: this.state.buildlist[0].label,
                                            });
                                        }
                                    }}>
                                    {this.state.buildName == '' ? '选择小区' : this.state.buildName}
                                </Text>
                            </Flex>
                            <Modal popup visible={this.state.visible} animationType="slide-up" onClose={this.onClose}>
                                <View
                                    style={{
                                        paddingVertical: 20,
                                        paddingHorizontal: 20,
                                    }}>
                                    <PickerView onChange={this.onChange} value={[this.state.buildId]} data={this.state.buildlist} cols={1} />
                                </View>
                                <Button type="primary" onPress={this.onClose}>
                                    确定
                                </Button>
                            </Modal>
                            {this.state.buildName === '其他' && (
                                <>
                                    <WhiteSpace size={'xs'} />
                                    <View style={styles.userviews}>
                                        <Text style={styles.userText}>其他楼盘</Text>
                                        <View style={styles.nameinputstyle}>
                                            <List>
                                                <InputItem placeholder="请输入其他楼盘名称" onChange={this.setbuildName} />
                                            </List>
                                        </View>
                                    </View>
                                </>
                            )}
                            <WhiteSpace size={'xs'} />
                            <View style={styles.userviews}>
                                <Text style={styles.userText}>门牌号</Text>
                                <View style={styles.nameinputstyle}>
                                    <List>
                                        <InputItem placeholder="请输入门牌号" onChange={setMen} />
                                    </List>
                                </View>
                            </View>
                        </View>
                        <WhiteSpace size={'xs'} />
                        <View
                            style={{
                                flex: 1,
                                justifyContent: 'center',
                                flexDirection: 'row',
                            }}>
                            <View style={styles.viewbutton}>
                                <Button onPress={onPress} type={'warning'} style={styles.button}>
                                    完成
                                </Button>
                            </View>
                        </View>
                    </View>
                </ScrollView>
            </>
        );
    }
}

export default connect(mapGetter, mapSetter)(Information);

const styles = StyleSheet.create({
    srcollview: {
        flex: 1,
    },
    userview: {
        flex: 1,
        flexDirection: 'row',
    },
    userText: {
        width: 100,
        height: 50,
        lineHeight: 50,
        textAlign: 'center',
        textAlignVertical: 'center',
        fontSize: 15,
    },
    userviews: {
        flexDirection: 'row',
        backgroundColor: '#FFFFFF',
        height: 50,
        justifyContent: 'center',
        alignItems: 'center',
    },
    meninputstyle: {
        justifyContent: 'center',
    },
    view: {
        flex: 1,
        flexDirection: 'column',
    },
    nameinputstyle: {
        width: '65%',
        textAlign: 'center',
        flexDirection: 'column',
        justifyContent: 'center',
    },
    titText: {
        fontSize: 20,
    },
    tituserview: {
        height: 50,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    button: {
        fontSize: 15,
    },
    viewbutton: {
        marginTop: '10%',
        width: '70%',
        height: 44,
        marginBottom: 50,
    },
    seleviews: {
        marginTop: 10,
        flexDirection: 'row',
    },
    seleview: {
        width: 80,
        height: 40,
    },
    selebutton: {
        fontSize: 15,
    },
});
